package cn.cctvcc.security.service;

import cn.cctvcc.core.constant.cache.CachePrefixConstants;
import cn.cctvcc.core.constant.Constants;
import cn.cctvcc.core.constant.cache.CacheTimeOutConstants;
import cn.cctvcc.core.domain.R;
import cn.cctvcc.core.enums.system.SysEmailSendTypeEnum;
import cn.cctvcc.core.enums.system.SysEmailTypeEnum;
import cn.cctvcc.core.utils.StringUtil;
import cn.cctvcc.email.service.EmailService;
import cn.cctvcc.redis.service.RedisService;
import cn.cctvcc.system.api.domain.SysEmail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @description: 邮箱验证
 * @author: Jiang
 * @create: 2021-09-29 12:15
 */
@Component
public class EmailTokenService {

    private final static long EXPIRE_TIME = CacheTimeOutConstants.EMAIL_EXPIRE;

    private final static String ACCESS_TOKEN = CachePrefixConstants.EMAIL_KEY;

    @Autowired
    private RedisService redisService;
    @Autowired
    private EmailService emailService;

    /**
     * 创建邮件验证码
     */
    public R<?> createKey(String email, String eamilType) {
        int randomNum = new Random().nextInt(999999);
        SysEmail sysEmail = new SysEmail();
        sysEmail.setToEmail(email);
        sysEmail.setSubject(Constants.PORJECT_NAME + " - " + SysEmailSendTypeEnum.getInfoByCode(eamilType) + "验证码");
        sysEmail.setContent("您的" + SysEmailSendTypeEnum.getInfoByCode(eamilType) + "验证码为：" + randomNum + ", 有效时间为2分钟，请尽快使用");
        sysEmail.setEmailType(SysEmailTypeEnum.普通邮件.getCode());
        // 发送邮件
        R emailResult = emailService.sendMail(sysEmail);
        if (Objects.equals(R.FAIL, emailResult.getCode()))
            throw new RuntimeException(emailResult.getMsg());

        // 保存验证码信息
        String emailKey = ACCESS_TOKEN + email;

        // 缓存验证码
        redisService.setCacheObject(emailKey, randomNum, EXPIRE_TIME, TimeUnit.MINUTES);

        return R.ok(null, Constants.SENDEMAIL_SUCCESS);
    }

    /**
     * 校验验证码
     */
    public boolean verifyKey(String email, String code) {
        // 获取缓存私钥
        Object o = redisService.getCacheObject(ACCESS_TOKEN + email);
        if (Objects.isNull(o))
            return false;
        String privateKey = o.toString();
        if (StringUtil.isEmpty(privateKey) || !Objects.equals(code, privateKey))
            return false;
        return true;
    }

}
